// ignore_for_file: must_call_super

import 'package:aitao_flutter/common_ui/empty_view.dart';
import 'package:aitao_flutter/home/controllers/home_controller.dart';
import 'package:aitao_flutter/home/views/home_item_widget.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/edgeInsets_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import '../../model/home_banner_model.dart';
import '../../model/home_item_model.dart';
import '../../pop_window/show_young_mode.dart';
import '../../refresh/custom_refresh_footer.dart';
import '../../refresh/custom_refresh_header.dart';
import '../../request/api.dart';
import '../../request/requestManager.dart';
import '../../routes/routes.dart';
import '../../style/text_style.dart';

class HomePage extends StatefulWidget {
  HomePage({Key? key}) : super(key: key);
  final HomeController controller = Get.put(HomeController());
  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with
        SingleTickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        WidgetsBindingObserver {
  late TabController tabController;
  final RefreshController refreshController =
      RefreshController(initialRefresh: false);

  List<HomeBannerModel> bannerList = [];
  List<HomeItemModel> itemList = [];
  int typeIndex = 0;
  int page = 1;
  int totalPage = 1;
  @override
  bool get wantKeepAlive => true;

  /// 加载图片的表示
  bool isLoadImage = true;
  @override
  Widget build(BuildContext context) {
    var scaleWidth = MediaQuery.of(context).size.width / 375.0;
    return GetBuilder<HomeController>(builder: ((controller) {
      return itemList.isEmpty
          ? EmptyView(
              emptyClickCallBack: () {
                debugPrint('刷新');
                loadNewList();
              },
            )
          : SmartRefresher(
              controller: refreshController,
              enablePullDown: true,
              enablePullUp: page < totalPage,
              onRefresh: onRefresh,
              onLoading: onLoading,
              header: CustomClassicHeader(),
              footer: const CustomClassicFooter(),
              child: CustomScrollView(
                slivers: [_bannerWidget(scaleWidth), _listWidget(context)],
              ),
            );
    }));
  }

  Widget _listWidget(BuildContext buildContext) {
    return SliverGrid(
        delegate: SliverChildBuilderDelegate((context, index) {
          return Padding(
              padding: EdgeInsetsStyle.customMargin(5, 5, 5, 5),
              child: isLoadImage
                  ? HomeItemWidget(
                      model: itemList[index],
                      itemClickCallBack: (model) {
                        HomeItemModel m = model;
                        Get.toNamed(Routes.personalPage,
                            parameters: {'userId': m.userid.toString()});
                      },
                    )
                  : const Text('加载中...'));
        }, childCount: itemList.length),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2, childAspectRatio: 0.9));
  }

  Widget _bannerWidget(double scaleWidth) {
    return SliverToBoxAdapter(
      child: Container(
          // height: 137 * scaleWidth + 5 + 44.w,
          padding: EdgeInsetsStyle.all(14),
          decoration: BoxDecoration(
              color: ColorStyle.whiteColor,
              borderRadius: RadiusStyle.radiusAll(5)),
          child: Column(
            children: [
              SizedBox(
                  height: 137 * scaleWidth,
                  child: Swiper(
                    // autoplay: true,
                    onTap: (index) {
                      String url = bannerList[index].linkUrl ?? '';
                      if (url == '') return;
                      Get.toNamed(Routes.webViewPage, parameters: {'url': url});
                    },
                    itemBuilder: (BuildContext context, int index) {
                      return Image.network(
                        SpUtil.getImageUrl(bannerList[index].image ?? ''),
                        fit: BoxFit.fill,
                      );
                    },
                    itemCount: bannerList.length,
                    pagination: const SwiperPagination(
                        builder: DotSwiperPaginationBuilder(
                            color: Color.fromRGBO(200, 200, 200, 0.5),
                            activeColor: ColorStyle.themeColor,
                            size: 8.0,
                            activeSize: 10.0)),
                  )),
              Box.vBox5,
              Container(
                  height: 44.w,
                  color: ColorStyle.whiteColor,
                  child: Row(
                    children: [
                      GestureDetector(
                        child: const Icon(Icons.search_outlined),
                        onTap: () {
                          Get.toNamed(Routes.searchPage);
                        },
                      ),
                      Box.hBox10,
                      Expanded(
                          child: TabBar(
                        // isScrollable: true,
                        unselectedLabelStyle: const TextStyle(
                            color: ColorStyle.ashGreyColor, fontSize: 15),
                        labelColor: ColorStyle.normalTextColor,
                        indicatorColor: ColorStyle.themeColor,
                        indicatorSize: TabBarIndicatorSize.label,
                        indicatorPadding:
                            const EdgeInsets.only(left: 8, right: 8),
                        indicatorWeight: 3,
                        labelPadding: const EdgeInsets.only(bottom: 5),
                        labelStyle: Styles.boldText_16,
                        tabs: widget.controller.tabList.map((e) {
                          return Padding(
                              padding:
                                  const EdgeInsets.only(left: 12, right: 12),
                              child: Text(
                                e.tr,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                              ));
                        }).toList(),
                        onTap: (index) {
                          changeIndex(index);
                        },
                        controller: tabController,
                      )),
                    ],
                  ))
            ],
          )),
    );
  }

  @override
  void initState() {
    super.initState();
    tabController = TabController(
        length: widget.controller.tabList.length, vsync: this, initialIndex: 0);
    getYoungMode();
    loadNewList();
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // AppLifecycleState.resumed: 应用在前台运行
    // AppLifecycleState.paused: 应用在后台运行
    SpUtil.saveAppLifeState(state == AppLifecycleState.resumed);
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void getYoungMode() {
    if (SpUtil.getYoungModeStatus()) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        //需要创建的小组件
        showDialog(
            barrierDismissible: false,
            context: Get.context!,
            builder: (builder) {
              return ShowYoundModeWindow(
                forgetCallBack: () {
                  debugPrint('忘记密码');
                },
                closeModeCallBack: () {
                  debugPrint('关闭');
                  Get.toNamed(Routes.closeYoungModePage);
                },
              );
            });
      });
    }
  }

  void loadNewList() async {
    var result = await RequestManager()
        .post(getRequestUrlByIndex(), params: {'page': page});
    if (result != null && result['code'] == 0) {
      // WJLogUtils.wjLog(result);
      bannerList.clear();
      itemList.clear();
      Map data = result['data'];
      List tempBanner = data['banner'];
      for (var banner in tempBanner) {
        HomeBannerModel bannerModel = HomeBannerModel.fromJson(banner);
        bannerList.add(bannerModel);
      }
      Map list = data['list'];
      page = int.parse(list['page'].toString());
      totalPage = int.parse(list['total_page'].toString());
      List tempList = data['list']['list'];
      for (var item in tempList) {
        HomeItemModel itemModel = HomeItemModel.fromJson(item);
        itemList.add(itemModel);
      }
      setState(() {});
    }
  }

  String getRequestUrlByIndex() {
    if (typeIndex == 0) {
      return API.homeHotUserList;
    } else if (typeIndex == 1) {
      return API.homeRecommendUserList;
    } else if (typeIndex == 2) {
      return API.homeAliveUserList;
    } else if (typeIndex == 3) {
      return API.homeNewUserList;
    } else {
      return API.homeHotUserList;
    }
  }

  void loadMoreList() async {
    var result = await RequestManager()
        .post(getRequestUrlByIndex(), params: {'page': page});
    if (result != null && result['code'] == 0) {
      Map data = result['data'];
      page = result['data']['list']['page'];
      totalPage = result['data']['list']['total_page'];
      List tempList = data['list']['list'];
      for (var item in tempList) {
        HomeItemModel itemModel = HomeItemModel.fromJson(item);
        itemList.add(itemModel);
      }
      setState(() {});
    }
  }

  void onRefresh() {
    page = 1;
    totalPage = 1;
    loadNewList();
    refreshController.refreshCompleted();
  }

  void onLoading() async {
    page += 1;
    loadMoreList();
    refreshController.loadComplete();
  }

  void changeIndex(int index) {
    if (index == typeIndex) return;
    typeIndex = index;
    page = 1;
    totalPage = 1;
    loadNewList();
  }
}

// class AppRouteObserver {
//   //这是实际上的路由监听器
//   static final RouteObserver<ModalRoute<void>> _routeObserver =
//       RouteObserver<ModalRoute<void>>();
//   //这是个单例
//   static final AppRouteObserver _appRouteObserver =
//       AppRouteObserver._internal();

//   AppRouteObserver._internal() {}
//   //通过单例的get方法轻松获取路由监听器
//   RouteObserver<ModalRoute<void>> get routeObserver {
//     return _routeObserver;
//   }

//   factory AppRouteObserver() {
//     return _appRouteObserver;
//   }
// }